<?php

namespace App\Http\Controllers\Api\Record;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Api\FillFirstVisitRequest;
use App\Models\MedicalAuxiliary;
use App\Models\MedicalComplaint;
use App\Models\MedicalRecord;
use App\Models\PastHistory;
use App\Project\Filters\ComplaintFilter;
use App\Project\Filters\PastHistoryFilter;
use Carbon\Carbon;
use Illuminate\Http\Request;

class RecordController extends ApiController
{
    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;

    public function __construct(Request $request)
    {
        parent::__construct();

        $this->request = $request;
    }

    /**
     * 创建首诊病历
     * @return \Illuminate\Http\JsonResponse
     */
    public function store()
    {
        $input = $this->request->input();

        $input['visit_type'] = 1;
        $input['clinic_at'] = Carbon::now()->toDateString();

        $result = MedicalRecord::create($input);

        return $this->response(['id' => $result['id']]);
    }

    public function fillInitial(FillFirstVisitRequest $request)
    {
        $result = [];

        \DB::transaction(function () use ($request, $result) {

            $past_input = (new PastHistoryFilter($request))->except('symptom');

            $result['past_id'] = PastHistory::updateOrCreate(
                ['record_id' => $past_input['record_id']], $past_input
            )->id;

            $complaint_input = (new ComplaintFilter($request))->get('only', ['record_id', 'symptoms']);

            $result['complaint_id'] = MedicalComplaint::updateOrCreate([
                'record_id' => $complaint_input['record_id']], $complaint_input
            )->id;
        });

        return $this->hasData($result);
    }

    /**
     * 创建复诊病历
     * @return \Illuminate\Http\JsonResponse
     */
    public function subsequent()
    {
        $input = $this->request->input();

        $input['visit_type'] = 0;
        $input['clinic_at'] = Carbon::now()->toDateString();

        $result = MedicalRecord::create($input);

        return $this->response(['id' => $result['id']]);
    }

    public function delete()
    {
        $this->validate($this->request, [
            'record_id' => 'required|integer|min:1'
        ]);

        $record_id = $this->request->input('record_id');

        $record = MedicalRecord::withoutGlobalScope('hasBindDoctor')->findOrFail($record_id);

        if ($record->isFirstVisit() && MedicalRecord::where(['patient_id' => \Auth::id(), 'visit_type' => 0])->count()) {
            return $this->setMessage('删除全部复诊后才能删除首诊。')->setCode(40300)->hasNoData();
        }

        return $this->responseForDelete($this->deleteWithRelation($record));
    }

    /**
     * @param \App\Models\MedicalRecord $record
     * @return boolean
     */
    protected function deleteWithRelation(MedicalRecord $record)
    {
        return \DB::transaction(function () use ($record) {
            $record->forceDelete();
            PastHistory::where('record_id', $record->id)->delete();
            MedicalComplaint::where('record_id', $record->id)->delete();
            MedicalAuxiliary::where('record_id', $record->id)->delete();

            return true;
        });
    }
}
